﻿using Infrastructure;
using Infrastructure.Repository.Sys;
using Model.DomainModel.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoreDomain.BusinessCore
{
    /// <summary>
    /// 部门核心类
    /// </summary>
    public static class DepartmentCore
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private static SysDepartmentRepository _sysDepartmentRepository = new();

        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        private static List<SysDepartment> GetALLDepartment(string corporationKey)
        {
            var allDepList = _sysDepartmentRepository.GetDepartmentByCorporationKey(corporationKey);
            return allDepList;
        }

        /// <summary>
        /// 根据部门id获取所有子集部门id
        /// </summary>
        /// <param name="id">部门ID</param>
        /// <param name="corporationKey">公司key</param>
        /// <returns>返回所有下级部门</returns>
        public static List<string> GetChildrenDepartmentIdById(string id, string corporationKey)
        {
            List<string> idList = new() { id };
            var allDepList = GetALLDepartment(corporationKey);
            foreach (var item in allDepList)
            {
                if (id == item.Pid)
                {
                    idList.Add(item.Id);
                    GetChildrenDepartmentId(item.Id, allDepList, idList);
                }
            }
            return idList;
        }

        /// <summary>
        /// 实现递归
        /// </summary>
        /// <param name="id">上级部门ID</param>
        /// <param name="sysDepartmentList">所有部门集合</param>
        /// <returns></returns>
        private static List<string> GetChildrenDepartmentId(string id, List<SysDepartment> sysDepartmentList, List<string> idList)
        {
            foreach (var item in sysDepartmentList)
            {
                if (id == item.Pid)
                {
                    idList.Add(item.Id);
                    GetChildrenDepartmentId(item.Id, sysDepartmentList, idList);
                }
            }
            return idList;
        }
    }
}
